﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;

namespace Kaixin.Tools
{
    public class TextOutput
    {
        private static TextBox _tb = null;
        private static ListBox _lb = null;

        public static void SetTextBox(TextBox tb)
        {
            _tb = tb;
        }

        public static void SetListBox(ListBox lb)
        {
            _lb = lb;
        }

        private delegate void PrintDelegate(string text);

        private static void TextBoxAddText(string text)
        {
            if (_tb.InvokeRequired)
            {
                _tb.Invoke(new PrintDelegate(TextBoxAddText), new object[] { text });
            }
            else
            {
                lock (_tb.Text)
                {
                    _tb.Text += text;
                    _tb.Select(_tb.Text.Length-1, 0);
                }
            }
        }

        private static void ListBoxAddText(string text)
        {
            if (_lb.InvokeRequired)
            {
                _lb.Invoke(new PrintDelegate(Print), new object[] { text });
            }
            else
            {
                lock (_lb.Items)
                {
                    int i = _lb.Items.Add(text);
                    _lb.SelectedIndex = i;
                }
            }
        }

         public static void Print(string text)
        {
            if (_tb != null)
            {
                TextBoxAddText(text);
            }

            if (_lb != null)
            {
                ListBoxAddText(text);
            }
        }

        public static void PrintLine(string text)
        {
            if (_tb != null)
            {
                TextBoxAddText(text + "\r\n");
            }

            if (_lb != null)
            {
                ListBoxAddText(text);
            }
        }

        public static void Clear()
        {
            if (_tb != null)
            {
                lock (_tb.Text)
                {
                    _tb.Text = "";
                }
            }

            if (_lb != null)
            {
                lock (_lb.Items)
                {
                    _lb.Items.Clear();
                }
            }
        }
    }
}
